import React, { useState, useEffect } from 'react';
import { TjContent, TjFilter, TjHeader, TjUpload } from '@/tjComponents';
import { useForm } from 'antd/es/form/Form';
import { DatePicker, Modal, Select, message, Button, Drawer } from 'antd';
import TjTable from '@/pages/ETrade/components/TjTable';
import moment from 'moment';
import {
  delRow,
  downLoadFile,
  getDownloadUrl,
  getList,
  uploadUrl,
  fetchFiletype,
  getMarketList,
} from './service';
import { columns, downFile, getFileType } from './helper';
import { useFullscreen, useSetState } from 'ahooks';
import {
  FullscreenExitOutlined,
  FullscreenOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { HttpCode } from '#/utils/contacts.js';
import TRDefault from '.././../../tool/components/TRTheme/TRDefault';
import { connect } from 'umi';
import Np from '@/utils/numberPrecision';
import type { RcFile } from 'antd/lib/upload';
import type { IFileInfoType } from '@/tjComponents/TjUpload/TjUploadContent';
import DrawerContent from './DrawerContent';

import './index.less';

const { RangePicker } = DatePicker;
const { confirm } = Modal;

const initValue = {
  fileType: '',
  time: [moment().startOf('month'), moment().endOf('month')],
  fileName: undefined,
};

const DataStorage: React.FC<IDataStorageProps> = (props) => {
  const [initFilterValue, setInitFilterValue] = useState<any>(null);
  const [req, setReq] = useSetState<any>({});
  const [fileTypeOptions, setFileTypeOptions] = useState<any>([]);
  const [province, setProvince] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = useForm();
  const [isFullscreen, { enterFullscreen, exitFullscreen }] = useFullscreen(() =>
    document.getElementById('dataStoragePreBox'),
  );
  const [dataSource, setDataSource] = useState<any>([]);
  const [uploadOtherParams, setUploadOtherParams] = useSetState<any>({
    date: moment().format('YYYY-MM-DD'),
    fileType: '',
    marketId: 'PHBSX',
  });
  const [preUrl, setPreUrl] = useState<string>();
  const [preType, setPreType] = useState<string>();
  const currentPreId = React.useRef<number>();

  const [drawerVisible, setDrawerVisible] = useState<boolean>();
  const [uploadFileTypeOptions, setUploadFileTypeOptions] = useState<any[]>([]);

  const onSearch = (val: any) => {
    setReq(val);
    // const obj: any = {};
    // if (val.fileType !== 0) {
    //   obj.fileType = val.fileType;
    // }
    // if (val.marketId !== 'all') {
    //   obj.marketId = val.marketId;
    // }
    // setUploadOtherParams(obj);
  };

  const onReset = (val: any) => {
    const newVal = {
      ...val,
      fileName: undefined,
    };
    setReq(newVal);
  };

  const preview = async (row: any) => {
    if (currentPreId.current === row.id) {
      return;
    }
    const type = getFileType(row.fileNameSuffixed);
    const fileUrl = getDownloadUrl(row.filePath);
    currentPreId.current = row.id;
    let url = fileUrl;
    if (type === 'notSupport') {
    } else {
      if (type === 'online') {
        url = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(fileUrl)}`;
      }
      if (type === 'download') {
        const data = await downLoadFile(row.filePath);
        if (data && !data.statusCode && data.size > 66) {
          const bolb = new Blob([data], { type: 'application/pdf;chartset=UTF-8' });
          url = URL.createObjectURL(bolb);
        } else {
          message.error('预览文件下载失败');
        }
      }
    }

    setPreUrl(url);
    setPreType(type);
  };

  const download = (row: any) => {
    const url = getDownloadUrl(row.filePath);
    downFile(url, row.fileName);
  };

  const del = (row: any) => {
    confirm({
      title: '确定要删除该条数据吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        delRow(row.id)
          .then((res: any) => {
            if (res.statusCode === HttpCode.SUCCESS) {
              message.success('删除成功');
              query();
            } else {
              message.error(res.msg);
            }
          })
          .catch(() => {
            setLoading(false);
          });
      },
    });
  };

  const query = () => {
    setLoading(true);
    const params = {
      ...req,
    };
    params.startDate = req.time[0].format('YYYY-MM-DD');
    params.endDate = req.time[1].format('YYYY-MM-DD');
    delete params.time;
    if (req.marketId === 'all') {
      params.marketId = undefined;
    }

    getList(params)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          setDataSource(res.data || []);
          setPreType(undefined);
          setPreUrl(undefined);
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const uploadSuccessCb = () => {
    // message.success('上传成功');
    query();
  };

  const beforeUploadRule = (file: RcFile): IFileInfoType => {
    const fileInfo: IFileInfoType = {
      name: file.name,
      size: file.size,
      uid: file.uid,
      lastModifiedDate: file.lastModifiedDate,
      uploadDate: moment().format('YYYY-MM-DD HH:mm:ss'),
    };
    const isLt50M = Np.divide(file.size, 1024, 1024) < 50;
    if (!isLt50M) {
      fileInfo.status = 'error';
      fileInfo.tipsMsg = '文件大小不能超过50M';
    }

    if (!uploadOtherParams.fileType) {
      fileInfo.status = 'error';
      fileInfo.tipsMsg = '文件类别不能为空';
    }

    return fileInfo;
  };

  const fetchFileTypeOptions = async (marketId: string, callback: any) => {
    const response = await fetchFiletype(marketId === 'all' ? undefined : marketId);
    if (response && response.statusCode === HttpCode.SUCCESS) {
      const list = response.data.map((item: any) => ({
        label: item.description,
        value: item.id,
        code: item.value,
      }));
      setFileTypeOptions(list);
      const firstFileType = list.length ? list?.[0] : null;
      setInitFilterValue({
        ...initFilterValue,
        fileType: 0,
      });
      callback && callback(firstFileType?.value ?? '');
    }
  };

  const onCloseDeptManager = () => {
    // fetchFileTypeOptions(req.marketId, (fileType: any) => {
    //   form.setFieldsValue({ fileType: 0 });
    //   // setUploadOtherParams({ fileType });
    //   setReq({ fileType: 0 });
    //   setDrawerVisible(false);
    // });
    setDrawerVisible(false);
    setReq({ fileType: 0 });
    changeMarketId(req.marketId, 'search');
  };

  const changeMarketId = async (val: any, type: string) => {
    const response = await fetchFiletype(val === 'all' ? undefined : val);
    if (response && response.statusCode === HttpCode.SUCCESS) {
      let list = [];
      if (response.data && response.data.length > 0) {
        list = response.data.map((item: any) => ({
          label: item.description,
          value: item.id,
          code: item.value,
        }));
      }

      if (type === 'search') {
        setFileTypeOptions(list);
        form.setFieldsValue({
          fileType: 0,
        });
      }
      if (type === 'upload') {
        setUploadFileTypeOptions(list);
        setUploadOtherParams({
          fileType: list.length > 0 ? list[0].value : undefined,
        });
      }
    }
  };

  const init = () => {
    setLoading(true);
    getMarketList()
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const list = res.treeList.map((v: any) => {
            return {
              ...v,
              label: v.title,
            };
          });
          setProvince(list);
          fetchFileTypeOptions('all', (fileType: any) => {
            const newParams = {
              marketId: 'all',
              ...initValue,
              fileType: 0,
            };
            // setUploadOtherParams({ fileType, marketId: 'PHBSX' });
            setInitFilterValue(newParams);
            setReq(newParams);
          });
        } else {
          setLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    init();
    changeMarketId('PHBSX', 'upload');
  }, []);

  useEffect(() => {
    if (req.marketId) {
      query();
      // setUploadOtherParams({
      //   marketId: req.marketId,
      // });
    }
  }, [req]);

  return (
    <div className="zlcc">
      <TjHeader
        left={
          <TjFilter
            defaultValues={initFilterValue}
            onReset={onReset}
            onSearch={onSearch}
            loading={loading}
            form={form}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={[{ label: '全国', value: 'all' }, ...province]}
                    allowClear={false}
                    style={{ width: 180 }}
                    loading={loading}
                    showSearch
                    filterOption={(input: string, option: any) => {
                      return (option?.label).toLowerCase().includes(input.toLowerCase());
                    }}
                    onChange={(val) => changeMarketId(val, 'search')}
                  />
                ),
              },
              {
                name: 'fileType',
                render: (
                  <Select
                    options={[
                      {
                        label: '全部',
                        value: 0,
                        code: '全部',
                      },
                      ...fileTypeOptions,
                    ]}
                    style={{ width: 180 }}
                    loading={loading}
                    allowClear={false}
                  />
                ),
              },
              {
                name: 'fileName',
                placeholder: '请输入文件名称',
              },
              { name: 'time', render: <RangePicker allowClear={false} /> },
            ]}
          />
        }
        right={
          <>
            <TjUpload
              uploadUrl={uploadUrl}
              loading={loading}
              hearder={
                <div>
                  <div>
                    <span>交易中心</span>
                    <Select
                      options={province}
                      style={{ width: 404, margin: '0px 0px 15px 10px' }}
                      value={uploadOtherParams.marketId}
                      showSearch
                      filterOption={(input: string, option: any) => {
                        return (option?.label).toLowerCase().includes(input.toLowerCase());
                      }}
                      onChange={(val) => {
                        setUploadOtherParams({
                          marketId: val,
                        });
                        changeMarketId(val, 'upload');
                      }}
                    />
                  </div>
                  <div>
                    <span>文件类别</span>
                    <Select
                      options={uploadFileTypeOptions}
                      style={{ width: 404, margin: '0px 0px 15px 10px' }}
                      value={uploadOtherParams.fileType}
                      onChange={(val) => {
                        setUploadOtherParams({
                          fileType: val,
                        });
                      }}
                    />
                  </div>
                </div>
              }
              uploadOtherParams={uploadOtherParams}
              uploadSuccessCb={uploadSuccessCb}
              beforeUploadRule={beforeUploadRule}
            />
          </>
        }
      />
      <TjContent className="content">
        <div className="content-header">
          <h1>资料列表</h1>
          <Button
            type="primary"
            onClick={() => {
              setDrawerVisible(true);
            }}
          >
            文件类别管理
          </Button>
        </div>
        <div className="content-body">
          <div className="left">
            <TjTable
              columns={columns({ preview, download, del })}
              dataSource={dataSource}
              isLoading={loading}
            />
          </div>
          <div className="right" id="dataStoragePreBox">
            <div className="preview-title">
              <span>预览</span>
              {preUrl && preType !== 'notSupport' && (
                <div>
                  {isFullscreen ? (
                    <FullscreenExitOutlined onClick={() => exitFullscreen()} />
                  ) : (
                    <FullscreenOutlined onClick={() => enterFullscreen()} />
                  )}
                </div>
              )}
            </div>
            <div className="preview-box">
              {preUrl && (preType === 'online' || preType === 'download') && (
                <iframe src={preUrl} className="iframe" />
              )}
              {preUrl && preType === 'img' && (
                <div className="img-box">
                  <img src={preUrl} />
                </div>
              )}
              {preUrl && preType === 'notSupport' && (
                <TRDefault type="emptysm" message="当前文件类型，需要下载至本地后方可预览" />
              )}
            </div>
          </div>
        </div>
      </TjContent>

      <Drawer
        title="文件类别管理"
        placement="right"
        onClose={() => onCloseDeptManager()}
        visible={drawerVisible}
        width="1164px"
        destroyOnClose
        maskClosable={false}
      >
        <DrawerContent marketList={province} />
      </Drawer>
    </div>
  );
};

interface IDataStorageProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(DataStorage);
